<?php

namespace app\common\repositories;

use app\common\model\store\product\Product;
use app\common\model\store\StoreCategory;
use crmeb\services\MiniProgramService;

class MiniShopRepository extends BaseRepository
{
    protected $access_token = '';

    public function __construct()
    {
        $this->access_token = MiniProgramService::create()->miniProgram()->access_token->getToken();
    }

    public function getCategoryList()
    {
        $cateList = cache('mini_shop_category_list');
        if (!$cateList) {
            $cateList = [];
            $result = self::request('https://api.weixin.qq.com/shop/cat/get?access_token=' . $this->access_token);
            if ($result['errcode'] == 0) {
                $third_cat_list = $result['third_cat_list'];
                foreach ($third_cat_list as $cate) {
                    if ($cate['qualification_type'] == 1 || $cate['product_qualification_type'] == 1) continue;
                    if (!isset($cateList[$cate['first_cat_id']])) {
                        $cateList[$cate['first_cat_id']] = [
                            'value' => $cate['first_cat_id'],
                            'label' => $cate['first_cat_name'],
                            'children' => [],
                        ];
                    }
                    if (!isset($cateList[$cate['first_cat_id']]['children'][$cate['second_cat_id']])) {
                        $cateList[$cate['first_cat_id']]['children'][$cate['second_cat_id']] = [
                            'value' => $cate['second_cat_id'],
                            'label' => $cate['second_cat_name'],
                            'children' => [],
                        ];
                    }
                    if (!isset($cateList[$cate['first_cat_id']]['children'][$cate['second_cat_id']]['children'][$cate['third_cat_id']])) {
                        $cateList[$cate['first_cat_id']]['children'][$cate['second_cat_id']]['children'][$cate['third_cat_id']] = [
                            'value' => $cate['third_cat_id'],
                            'label' => $cate['third_cat_name'],
                        ];
                    }
                }
                $cateList = array_values($cateList);
                foreach ($cateList as $f_k => $f) {
                    $cateList[$f_k]['children'] = array_values($f['children']);
                    foreach ($cateList[$f_k]['children'] as $s_k => $s) {
                        $cateList[$f_k]['children'][$s_k]['children'] = array_values($s['children']);
                    }
                }
                cache('mini_shop_category_list', $cateList, 86400);
            }
        }
        return $cateList;
    }

    public function setProduct($id, $c = true)
    {
        $data = Product::getDB()->where('product_id', $id)->find();
        $product = [
            'out_product_id' => $data['product_id'],
            'title' => $data['store_name'],
            'path' => 'pages/goods_details/index?id=' . $data['product_id'],
            'head_img' => [$data['image']],
            'third_cat_id' => StoreCategory::getDB()->where('store_category_id', $data['cate_id'])->value('mini_shop_cate_id'),
            'brand_id' => 2100000000,
            'skus' => [[
                'out_product_id' => $data['product_id'],
                'out_sku_id' => $data['product_id'],
                'thumb_img' => $data['image'],
                'sale_price' => intval(bcmul($data['price'], 100, 0)),
                'market_price' => intval(bcmul($data['ot_price'], 100, 0)),
                'stock_num' => $data['stock'],
                'sku_attrs' => [[
                    'attr_key' => '默认',
                    'attr_value' => '默认'
                ]]
            ]]
        ];
        // 查询商品状态
        $result = self::request('https://api.weixin.qq.com/shop/spu/get?access_token=' . $this->access_token, 'post', [
            'out_product_id' => $id
        ]);
        // 新建商品
        if ($result['errcode'] == 1000011) {
            $result = self::request('https://api.weixin.qq.com/shop/spu/add?access_token=' . $this->access_token, 'post', $product);
        }
        // 更新操作
        elseif ($c) {
            $result = self::request('https://api.weixin.qq.com/shop/spu/update?access_token=' . $this->access_token, 'post', $product);
        }
        // 未上架状态
        elseif (isset($result['spu']) && $result['spu']['status'] != 5) {
            $result = self::request('https://api.weixin.qq.com/shop/spu/listing?access_token=' . $this->access_token, 'post', [
                'out_product_id' => $id
            ]);
        }
        return $result;
    }

    public function setStatus($id, $status)
    {
        // 上下架
        if ($status) {
            $result = self::request('https://api.weixin.qq.com/shop/spu/listing?access_token=' . $this->access_token, 'post', [
                'out_product_id' => $id
            ]);
        } else {
            $result = self::request('https://api.weixin.qq.com/shop/spu/delisting?access_token=' . $this->access_token, 'post', [
                'out_product_id' => $id
            ]);
        }
        return $result;
    }

    /**
     * curl 请求
     * @param string $url 请求地址
     * @param string $method 请求方式
     * @param array $data 请求数据
     * @param bool $header 请求header头
     * @param int $timeout 超时秒数
     * @return bool|string
     */
    public static function request($url, $method = 'post', $data = array('1' => '1'), $header = false, $timeout = 15)
    {
        $curl = curl_init($url);
        $method = strtoupper($method);
        //请求方式
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        //post请求
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        //设置header头
        // if ($header !== false)
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen(json_encode($data, JSON_UNESCAPED_UNICODE))
            )
        );
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        //返回抓取数据
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        //输出header头信息
        curl_setopt($curl, CURLOPT_HEADER, true);
        //TRUE 时追踪句柄的请求字符串，从 PHP 5.1.3 开始可用。这个很关键，就是允许你查看请求header
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
        //https请求
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
        $content = trim(substr($content, $status['header_size']));
        return (intval($status["http_code"]) === 200) ? json_decode($content, true) : false;
    }
}